package com.streetlight.lampcursor.ui.settings

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.lampcursor.streetlight.databinding.FragmentSettingsBinding
import com.streetlight.lampcursor.model.SettingsData

class SettingsFragment : Fragment() {

    private var _binding: FragmentSettingsBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: SettingsViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupViews()
        setupObservers()
        setupClickListeners()
        
        // 初始加载数据
        viewModel.loadSettings()
    }

    private fun setupViews() {
        // 初始化视图状态
    }

    private fun setupObservers() {
        viewModel.settings.observe(viewLifecycleOwner) { settings ->
            updateSettings(settings)
        }
        
        viewModel.saveResult.observe(viewLifecycleOwner) { result ->
            when (result) {
                is SettingsViewModel.SaveResult.Success -> {
                    Toast.makeText(context, "设置已保存", Toast.LENGTH_SHORT).show()
                }
                is SettingsViewModel.SaveResult.Error -> {
                    Toast.makeText(context, "保存失败: ${result.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun setupClickListeners() {
        binding.btnSaveSettings.setOnClickListener {
            saveSettings()
        }
    }

    private fun updateSettings(settings: SettingsData) {
        binding.switchAutoBrightness.isChecked = settings.autoBrightness
        binding.switchMotionSensor.isChecked = settings.motionSensor
        binding.switchWeatherAdaptation.isChecked = settings.weatherAdaptation
        binding.etServerAddress.setText(settings.serverAddress)
        binding.etDeviceId.setText(settings.deviceId)
    }

    private fun saveSettings() {
        val settings = SettingsData(
            autoBrightness = binding.switchAutoBrightness.isChecked,
            motionSensor = binding.switchMotionSensor.isChecked,
            weatherAdaptation = binding.switchWeatherAdaptation.isChecked,
            serverAddress = binding.etServerAddress.text.toString(),
            deviceId = binding.etDeviceId.text.toString()
        )
        
        viewModel.saveSettings(settings)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 